/**
 * 
 */
package cn.jhz.filesharingsystem.web;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.jhz.filesharingsystem.model.Permission;
import cn.jhz.filesharingsystem.model.Role;
import cn.jhz.filesharingsystem.model.User;
import cn.jhz.filesharingsystem.service.UserService;
import cn.jhz.filesharingsystem.util.SecurityUtil;

/**
 * @author asus
 *
 */
public class AutoLoginInterceptor extends HandlerInterceptorAdapter{

	@Autowired
	UserService userService;
	//具体的拦截功能
	//自动登录
	//基本思路：判断请求中有没有cookie,userkey,ssid是否正确
	//跳转main 同时把userkey放入session		
	//没有关键cookie,转发请求,让页面正常执行登录
	
	
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler)
			throws Exception {
		HttpSession session = req.getSession();
		ServletContext servletContext = session.getServletContext();
		Cookie cookies[] = req.getCookies();
			
		
		
		if(session.getAttribute("loginUser") == null) {
			String email = null;
			String ssid = null;
			if(cookies !=null && cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if(cookie.getName().equals("userKey")) {
						email = cookie.getValue();
					}else if(cookie.getName().equals("ssid")) {
						ssid = cookie.getValue();
					}
				}              

				if(email != null && ssid != null && ssid.equals(SecurityUtil.md5$sha_x(email))) {
					
					
					//将新的session放入	
					servletContext.setAttribute(email, session);
					
					
					User user = userService.login(email);
					session.setAttribute("loginUser", user);
					
					
					//实现登录
					Role role = user.getRole(); //拿到登录成功的用户所有关联的所有角色信息
					boolean isadmin = false; //是：true，不是：false
					Set<String> userAllpermRes = new HashSet<>(); //权限标记
					Set<Permission> permissions;    //角色对应权限url
					
					//判断一下登录成功的用户是不是超级管理员
					if("super".equals(role.getRoleName())) {
						isadmin = true;// 标记改true
					}else {
						//不是超级管理员的情况下，我们要把登录成功的用户，关联的所有权限标记，取出来
						permissions = role.getPermissions();
						for(Permission permission : permissions) {
							userAllpermRes.add(permission.getResource());
						}
					}	
					//判断完毕后，userAllpermRes：包括了登录成功的用户，所拥有的所有权限的标记
					session.setAttribute("isadmin", isadmin);
					if(!isadmin) {
						session.setAttribute("userAllPermRes", userAllpermRes);
					}
				}
			}
		}
		return super.preHandle(req, resp, handler);
	}

}
